<template>
    <section>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form :model="formDataAdd" :rules="rulesAdd" ref="formAdd" label-width="100px" class="formAdd">
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="formDataAdd.username" placeholder="请输入用户名" type="text"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                  <el-input v-model="formDataAdd.password" placeholder="请输入密码" type="password"></el-input>
                </el-form-item>
                <el-form-item label="头像" prop="icon">
                  <!-- <el-input v-model="formDataAdd.icon" placeholder="头像" type="password"></el-input> -->
                  <pic-sel style="float:left" v-model="formDataAdd.icon" />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="formDataAdd.email" placeholder="请输入邮箱" type="text"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="mobile">
                  <el-input v-model="formDataAdd.mobile" placeholder="请输入手机号" type="text"></el-input>
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                  <el-input v-model="formDataAdd.nickName" placeholder="请输入昵称" type="text"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop="roleIds">
                  <el-select v-model="formDataAdd.roleIds" multiple placeholder="请选择" @change="changeRole">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.roleName" :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="备注" prop="note">
                  <el-input v-model="formDataAdd.note" placeholder="请输入备注信息" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                  <el-select class="w200 ml10" v-model="formDataAdd.type" placeholder="选择管理员类型" @change="changeType"
                    clearable>
                    <el-option v-for="item in typeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="账号状态" prop="status">
      
                  <el-radio-group v-model="formDataAdd.status">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">启用</el-radio>
                  </el-radio-group>
                </el-form-item>
                <!-- <el-form-item label="合伙人ID" prop="partnerId">
                  <el-input v-model="formDataAdd.partnerId" placeholder="请输入合作人ID" type="text"></el-input>
                </el-form-item>
                <el-form-item label="小店ID" prop="sellerId">
                  <el-input v-model="formDataAdd.sellerId" placeholder="请输入小店ID" type="text"></el-input>
                </el-form-item> -->
                <el-form-item label="服务经理" prop="serviceManager">
      
                  <el-radio-group v-model="formDataAdd.serviceManager">
                    <el-radio :label="0">不是</el-radio>
                    <el-radio :label="1">是</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="绑定会员id" prop="memberId" v-if="formDataAdd.serviceManager">
                  <el-select v-model="formDataAdd.memberId" filterable remote reserve-keyword placeholder="请输入绑定会员id"
                    :remote-method="getMemberList" :loading="loading">
                    <el-option v-for="item in memberIdList" :key="item.id" :label="item.id" :value="item.id">
                    </el-option>
                  </el-select>
                  <!-- <el-input v-model="formDataAdd.memberId" placeholder="请输入绑定会员id" type="text"></el-input> -->
                </el-form-item>
      
      
      
                <el-form-item style="display: flex; justify-content: flex-end; width: 100%">
                  <el-button type="primary" @click="submitAdd">确定</el-button>
                  <!-- <el-button @click="cancel">取消</el-button> -->
                </el-form-item>
              </el-form>
          </el-col>
        </el-row>
    </section>
  </template>
  
  <script>
      import {
          admin_update_password
      } from '../../api/user';
      import {
  adminList,
  adminInfo,
  adminUpdate,
  adminAdd,
  updatePassword,
  updateMyPassword,
  adminDelete,
  updateStatus,
  roleUpdate,
  roleListAll,
  getRole,
  adminRoleUpdate
} from '@/api/admin'
import {
  member_list
} from '@/api/member'
      export default {
        components: {
    'pic-sel': () => import('../../components/PicSel/index')
  },
      data() {
          return {
            rulesAdd: {
        username: [
          { required: true, message: '用户名必填', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '类型必需选择', trigger: 'blur' },
        ],
        roleIds: [
          { required: true, message: '角色必需选择', trigger: 'blur' },
        ],
      },
      typeList: [
        { id: 1, name: '平台用户' },
        { id: 2, name: '合伙人用户' },
        { id: 3, name: '小店用户' }
      ],
      formData: {
        id: 0,
        username: '',
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      formRole: {
        adminId: 0,
        roleIds: []
      },
      formDataAdd: {
        id: '',
        username: '',
        password: '',
        icon: '',
        email: '',
        nickName: '',
        note: '',
        status: 1,
        type: undefined,   //类型，1：平台用户，2：合伙人用户，3小店用户
        typeText: '',
        partnerId: '',
        sellerId: '',
        createBy: '',
        updateBy: '',
        serviceManager: 0,
        memberId: '',
        mobile: '',
        roleIds: [],
        roleIdsText: ''
      },
      roleList: [],
      role: '',
      adminid:'',
      memberIdList: [],
              passwordForm: {
                  oldPassword: undefined,
                  password: undefined,
                  confirmPassword: undefined
              },
              saveLoading: false,
              passwordRules: {
                  oldPassword: [
                      {
                          required: true,
                          message: '请输入原始密码',
                          trigger: 'blur'
                      }
                  ],
                  password: [
                      {
                          required: true,
                          message: '请输入密码',
                          trigger: 'blur'
                      },
                      {
                          min: 5,
                          max: 20,
                          message: '长度在 5 到 20 个字符',
                          trigger: 'blur'
                      }
                  ],
                  confirmPassword: [
                      {
                          required: true,
                          message: '请输入确认密码',
                          trigger: 'blur'
                      },
                      {
                          min: 5,
                          max: 20,
                          message: '长度在 5 到 20 个字符',
                          trigger: 'blur'
                      }
                  ]
              }
          }
      },
      mounted() {
        this.adminid = sessionStorage.getItem('LOGIN_USERNAME_id')
        this.editDialog(this.adminid);
      },
      methods: {
          next() {
              const set = this.$refs;
              set["passwordForm"].validate(valid => {
                  if (valid) {
                      admin_update_password(this.passwordForm).then(() => {
                          this.$message.success("密码已修改");
                          this.passwordForm = {
                              oldPassword: undefined,
                              password: undefined,
                              confirmPassword: undefined
                          }
                      });
                  } else {
                      return false;
                  }
              });
          },
          remoteMethod() { },
    changeType(e) {
      console.log(e, this.typeList.find(item => item.id == e).name)
      this.formDataAdd.type = e
      this.formDataAdd.typeText = this.typeList.find(item => item.id == e).name
    },
    // 搜索
    handleFilter() {
      this.listQuery.pageNum = 1;
      this.getAdminList();
    },
    tc() {
      return "text-align:center; color:#333333; font-size:12px;";
    },
    tccolor() {
      return "text-align:center;background-color:#f5f5f5; font-size:14px;";
    },
    handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getAdminList();
            },
    // 取消
    cancel() {
      this.dialogVisible = false
      // this.$refs['form'].clearValidate()
      this.formData = {
        id: 0,
        username: '',
        oldPassword: '',
        password: '',
        confirmPassword: ''
      }
    },



    // 获取角色列表
    getRoleList() {
      roleListAll().then(res => {
        if (res.code === 200) {
          // res.data.data.forEach(item => {
          //   item.last_time_text = item.last_time || '无'
          // })
          console.log(res)
          this.roleList = res.data
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 修改信息弹窗
    editDialog(id) {
    //   this.dialogTitle = "修改"
      let sid = id
      this.getRoleList()
      // this.getRole(id)
      if (id) {
        adminInfo(sid).then(res => {
          console.log(res)
          if (res.code === 200) {
            // this.$message.success('修改成功')
            this.formDataAdd = res.data

            this.formDataAdd.type === 1 ? this.formDataAdd.typeText = "平台用户" : this.formDataAdd.type === 2 ? this.formDataAdd.typeText = "合伙人用户" : this.formDataAdd.typeText = '小店用户'

            this.dialogVisibleAdd = true
            this.formDataAdd.password = ''
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },


    // 修改密码
    submit() {

      this.$refs['form'].validate(valid => {
        if (valid) {
          updatePassword(this.formData).then(res => {
            console.log(res)
            if (res.code === 200) {
              this.$message.success('修改成功')
              this.formData = {
                id: 0,
                username: '',
                oldPassword: '',
                password: '',
                confirmPassword: ''
              }
              this.dialogVisible = false
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },
    // 新增
    submitAdd() {
      this.$refs['formAdd'].validate(valid => {
        if (valid) {
          if (this.formDataAdd.serviceManager) {

            this.formDataAdd.memberId ? '' : this.$message.error('请输入绑定会员id')
            return false
          }
          if (this.formDataAdd.id) {
            adminUpdate(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('修改成功')

                this.dialogVisibleAdd = false
              } else {
                this.$message.error(res.message)
              }
            })
          } else {
            if (this.formDataAdd.password.length < 8) {
              this.$message.error('密码至少为8个字符')
              return false
            }
            adminAdd(this.formDataAdd).then(res => {
              console.log(res)
              if (res.code === 200) {
                this.$message.success('创建成功')
                this.getAdminList()
                this.dialogVisibleAdd = false
              } else {
                this.$message.error(res.message)
              }
            })
          }
        }
      })
    },
    // 删除
    deleteadmin(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminDelete(id).then(res => {
          if (res.code === 200) {
            this.getAdminList()
            this.$message.success(res.message)
          } else {
            this.$message.error(res.message)
          }
        })
      }).catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                ? '已经取消删除'
                : '停留在当前页面'
            })
          });

    },
    // 检测两次密码是否一致
    checkConfirmPassword(rule, value, callback) {
      if (value !== this.formData.new_password) {
        return callback(new Error('两次输入的密码不一致'))
      } else {
        return callback()
      }
    },
    // 修改状态
    switchStatus(e, id) {

      let data = {
        status: Number(e)
      }

      console.log(e, id, data)
      updateStatus(data, id).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('修改成功')
          this.getRoleList()
        } else {
          this.$message.error(res.message)
        }
      })


    },
    changeRole(e) {
      console.log(e, this.formDataAdd.roleIds)

    },
    // 获取列表
    getAdminList() {
      console.log("会员列表")
      adminList(this.listQuery).then(res => {
        if (res.code === 200) {
          console.log("会员列表", res)
          this.tableData = res.data.list
          this.total = res.data.total
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // 修改密码按钮
    openDialog(row) {

      this.dialogVisible = true
      this.formData.id = row.id
      this.formData.username = row.username
    },
    // 分页
    pageChange(page) {
      this.form.page = page
      this.getAdminList()
    },
    // 搜索指定会员id
    getMemberList(e) {
      console.log(e)
      if (e) {
        let data = {
          keyword: e
        }
        member_list(data).then(res => {
          console.log(res)
          this.memberIdList = res.data.list
        })
      }

    },
    // 新增按钮
    addAccount() {
      this.getRoleList()
      this.formDataAdd = {
        id: '',
        username: '',
        password: '',
        icon: '',
        email: '',
        nickName: '',
        note: '',
        status: 1,
        type: '',
        partnerId: '',
        sellerId: '',
        createBy: '',
        updateBy: '',
        serviceManager: 0,
        memberId: '',
        mobile: ''
      }
      this.dialogTitle = '新增管理员'
      this.dialogVisibleAdd = true
    },
    // 重置密码
    resetPassword(id) {
      let data = {
        id: id,
        password: '123456'
      }


      updatePassword(data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message.success('重置成功')

        } else {
          this.$message.error(res.message)
        }
      })
    }
  
      }
      };
  </script>
  